using Domain.BOM;
using Domain.生产订单;
using Infratructure;
using Microsoft.AspNetCore.SignalR;
using Team.API.Hubs;
using Yitter.IdGenerator;

namespace Team.API.Services
{
    /// <summary>
    /// 自动创建订单后台服务
    /// 每小时自动创建一个测试订单
    /// </summary>
    public class AutoCreateOrderBackgroundService : BackgroundService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly IHubContext<EquipmentStatusHub> _hubContext;
        private readonly ILogger<AutoCreateOrderBackgroundService> _logger;
        private readonly TimeSpan _interval = TimeSpan.FromHours(1); // 每小时执行一次

        public AutoCreateOrderBackgroundService(
            IServiceProvider serviceProvider,
            IHubContext<EquipmentStatusHub> hubContext,
            ILogger<AutoCreateOrderBackgroundService> logger)
        {
            _serviceProvider = serviceProvider;
            _hubContext = hubContext;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("自动创建订单服务已启动");

            // 延迟15秒后开始执行，避免与其他服务冲突
            await Task.Delay(TimeSpan.FromSeconds(15), stoppingToken);

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    await CreateAutoOrder(stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "自动创建订单时发生错误");
                }

                // 等待1小时后再次执行
                await Task.Delay(_interval, stoppingToken);
            }

            _logger.LogInformation("自动创建订单服务已停止");
        }

        /// <summary>
        /// 自动创建订单
        /// </summary>
        private async Task CreateAutoOrder(CancellationToken cancellationToken)
        {
            using var scope = _serviceProvider.CreateScope();

            var orderRep = scope.ServiceProvider.GetRequiredService<IRepository<OrderModel>>();
            var bomRep = scope.ServiceProvider.GetRequiredService<IRepository<Bomtable>>();

            var currentTime = DateTime.Now;
            _logger.LogInformation($"开始自动创建订单 - {currentTime:yyyy-MM-dd HH:mm:ss}");

            try
            {
                // 获取所有可用的成品（BOM表中的成品）
                var availableItems = await bomRep.GetAll()
                    .Where(x => !x.IsDel) 
                    .ToListAsync();

                if (!availableItems.Any())
                {
                    _logger.LogWarning("没有可用的成品，无法创建订单");
                    return;
                }

                // 随机选择一个
                var random = new Random();
                var selectedItem = availableItems[random.Next(availableItems.Count)];

                // 随机生成订单数量（50-200之间）
                var orderNumber = random.Next(50, 201);

                // 创建订单
                var order = new OrderModel
                {
                    Id = YitIdHelper.NextId(),
                    Itemcode = selectedItem.Id,
                    Number = orderNumber,
                    Ordertime = currentTime,
                    Orderstatus = 0, // 待排程
                    IsDel = false
                };

                var result = await orderRep.AddAsync(order);

                if (result > 0)
                {
                    var message = $"自动创建订单成功: 成品={selectedItem.Goodsname}, 数量={orderNumber}";
                    _logger.LogInformation(message);

                    // 通过SignalR推送订单创建消息给所有客户端
                    await _hubContext.Clients.All.SendAsync(
                        "ReceiveAutoOrderCreated",
                        new
                        {
                            Time = currentTime,
                            OrderId = order.Id,
                            Itemcode = selectedItem.Id,
                            Number = orderNumber,
                            Message = message,
                            Source = "自动创建"
                        },
                        cancellationToken);

                    _logger.LogInformation("订单创建消息已通过SignalR推送");
                }
                else
                {
                    _logger.LogWarning("自动创建订单失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "自动创建订单失败");

                // 推送错误消息
                await _hubContext.Clients.All.SendAsync(
                    "ReceiveAutoOrderError",
                    new
                    {
                        Time = currentTime,
                        Message = $"自动创建订单失败: {ex.Message}",
                        Source = "自动创建"
                    },
                    cancellationToken);
            }
        }
    }
}
